package com.huluobo.mvvm_base.db;

import android.app.Application;

import androidx.room.Room;

/**
 * Created by LC on 2024/3/26.
 * Room数据库总结:
 * 1.给一个实体类添加表的注解@Entity,注意修改表名,同时加上主键 PrimaryKey
 * 2.创建Dao(接口) 写对应表的增删改查方法,注意加注解@Dao 增加的方法需要添加冲突策略
 * 3.创建数据库抽象类,主要在注解中写数据库的版本,和添加所有的表,同时添加返回Dao的方法
 * 4.创建数据库工具类,初始化时实例数据库
 */
public class AppDBUtils {
    private static final String DATABASE_NAME = "dou_yin.db";

    private static AppDBUtils appDBUtils;

    private AppDatabase appDatabase;
    private UserDao userDao;
    private MoneyDao moneyDao;

    private VideoDao videoDao;

    private AppDBUtils() {

    }

    public static AppDBUtils getInstance() {
        if (appDBUtils == null) {
            synchronized (AppDBUtils.class) {
                if (appDBUtils == null) {
                    appDBUtils = new AppDBUtils();
                }
            }
        }
        return appDBUtils;
    }

    //数据库初始化,记得调用
    public void init(Application application) {
        appDatabase = Room.databaseBuilder(application, AppDatabase.class, DATABASE_NAME)
                .allowMainThreadQueries()//允许主线程查询
                .build();
        userDao = appDatabase.getUserDao();
        moneyDao = appDatabase.getMoneyDao();
        videoDao = appDatabase.getVideoDao();
    }

    public UserDao getUserDao() {
        if (userDao == null) {
            userDao = appDatabase.getUserDao();
        }
        return userDao;
    }

    public MoneyDao getMoneyDao() {
        if (moneyDao == null) {
            moneyDao = appDatabase.getMoneyDao();
        }
        return moneyDao;
    }

    public VideoDao getVideoDao() {
        if (videoDao == null) {
            videoDao = appDatabase.getVideoDao();
        }
        return videoDao;
    }
}
